package com.dlm.controller;

import com.dlm.dao.Users;
import com.dlm.dto.BaseDto;
import com.dlm.sdk.api.OpenIdApi;
import com.dlm.service.IUsersService;
import com.dlm.service.impl.UsersServiceImpl;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * Created by chongsong on 15/2/1.
 * <mailto>chong.song@autonavi.com</mailto>
 */
public class BaseController extends Controller{
    protected IUsersService usersService = new UsersServiceImpl();

    public BaseDto makeDto(int code,String messge,Model data){
        BaseDto dto = new BaseDto();
        dto.setCode(code);
        dto.setMessage(messge);
        dto.setData(data);
        return dto;
    }

    public BaseDto makeDtoPage(int code,String messge,Page page){
        BaseDto dto = new BaseDto();
        dto.setCode(code);
        dto.setMessage(messge);
        dto.setData(page.getList());
        dto.setPageNumber(page.getPageNumber());
        dto.setPageSize(page.getPageSize());
        dto.setTotalPage(page.getTotalPage());
        dto.setTotalRow(page.getTotalRow());
        return dto;
    }

    public BaseDto makeDtoList(int code,String messge,List list){
        BaseDto dto = new BaseDto();
        dto.setCode(code);
        dto.setMessage(messge);
        dto.setData(list);
        return dto;
    }

    public void findUser(){
        String code = getPara("code");
        System.out.println("******* code:" + code);
        if(StringUtils.isNotBlank(code) && StringUtils.isBlank((String)getSession().getAttribute("openid"))){
            String openid = OpenIdApi.getOpenIdByCode(code);
            getSession().setAttribute("openid", openid);
            Users user = usersService.findUserByOpenid(openid);
            if(user != null){
                getSession().setAttribute("name", user.getStr(Users.nickname));
                if(user.getLong(Users.tel) > 0){
                    getSession().setAttribute("phone",user.get(Users.tel));
                    redirect("/#/user/coupon");
                }
            }
        }
    }
}
